// pages/pallet_details/pallet_details.js
var app = getApp();
var priceMap = {};//价格组，传给后台
var tcity = require("../../utils/citys.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pallet_select: false,
    options: 0,
    options_value: '5T',
    time: '00:00',
    date: "2018-1-1",
    times: '00:00',
    dates: "2018-1-1",
    provinces: [],
    zprovince: "",
    xprovince: "",
    citys: [],
    zcity: "",
    xcity: "",
    countys: [],
    zcounty: '',
    xcounty: '',
    value: [0, 0, 0],
    values: [0, 0, 0],
    condition: false,
    model:[],
    price2group: [],//价格组，用于判断格式
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    console.log("onLoad");
    var that = this;

    tcity.init(that);

    var cityData = that.data.cityData;


    const provinces = [];
    const citys = [];
    const countys = [];

    for (let i = 0; i < cityData.length; i++) {
      provinces.push(cityData[i].name);
    }
    console.log('省份完成');
    for (let i = 0; i < cityData[0].sub.length; i++) {
      citys.push(cityData[0].sub[i].name)
    }
    console.log('city完成');
    for (let i = 0; i < cityData[0].sub[0].sub.length; i++) {
      countys.push(cityData[0].sub[0].sub[i].name)
    }

    that.setData({
      'provinces': provinces,
      'citys': citys,
      'countys': countys,
      'zprovince': cityData[0].name,
      'zcity': cityData[0].sub[0].name,
      'zcounty': cityData[0].sub[0].sub[0].name,
      'xprovince': cityData[0].name,
      'xcity': cityData[0].sub[0].name,
      'xcounty': cityData[0].sub[0].sub[0].name
    })
    console.log('初始化完成');
    
    // 授权
    app.getLoginSession(function (session) {
      //获取路线列表
      wx.request({
        url: app.api + '/wx_log_test/sys/transport',
        data: {
          token: session
        },
        success: function (res) {
          var res = res.data;
          if (res.msg == "OK") {
            var data = res.data;
            if (data.length > 0) {
              that.setData({
                zhuangline: data,
                xieline: data,
              })
            } else {
              that.setData({
                zhuangline: [{ id: 1, name: '暂无路线' }],
                xieline: [{ id: 1, name: '暂无路线' }]
              })
            }
          }
        }
      });
      //获取分组
      wx.request({
        url: app.api +'/wx_log_test/sys/group',
        data:{
          token:session
        },
        success:function(res){
          var res = res.data;
          if(res.msg=="OK"){
            var data = res.data;
            console.log(data);
            that.setData({
              group:data
            })
            var price2group = that.data.price2group;
            for (var i = 0; i <data.length;i++){
              price2group.push({id:data[i].id,price:''});
              that.setData({
                price2group:price2group
              })
            }
          }
        }
      })
    })
    //获取车型
    // 授权
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + "/wx_log_test/sys/vehicle?token="+session,
        success:function(res){
          var model = that.data.model;
          for (var i = 0; i < res.data.data.length;i++){
            model.push(res.data.data[i].value);
            that.setData({
              model: model
            })
            console.log(res.data.data[i].value);
          }
        }
      })
    })
  },
  // 实时获取用户输入
  input: function (event) {
    var that = this;
    var value = event.detail.value;
    var type = event.currentTarget.dataset.type;
    if (type == 'goodsnew') {
      this.setData({
        goodsnew: value
      })
    } else if (type == 'goodsweight') {
      this.setData({
        goodsweight: value
      })
    } else if (type == 'goodaprice') {
      for (var i = 0; i < this.data.price2group.length; i++) {
        if (this.data.price2group[i].id == event.currentTarget.dataset.id){
          this.data.price2group[i].price = value;
          this.setData({
            price2group:that.data.price2group
          })
          priceMap[this.data.price2group[i].id] = this.data.price2group[i].price;//由于后台对价格组的要求，所以再赋值一次
        }
        console.log(priceMap);
      }
    } else if (type == 'goodsdata') {
      this.setData({
        'goodsdata': value
      })
    } else if (type == 'tips') {
      this.setData({
        'tips': value
      })
      console.log(value);
    } else if (type == 'length') {
      this.setData({
        'length': value
      })
      console.log(value);
    } else if (type == 'payload') {
      this.setData({
        'payload': value
      })
      console.log(value);
    } else if (type == 'volume') {
      this.setData({
        'volume': value
      })
    }
  },
  // 用户输入验证
  virifi: function () {
    var that = this;
    var error = '';
    var options = that.data.options;

    // if (!that.data.zname || that.data.zname == '') {
    //   error = '请输入装货地联系人';
    // } else if (!that.data.zphone_mob || that.data.zphone_mob == '' || !/^1[34578][0-9]{9}$/.test(that.data.zphone_mob)) {
    //   error = '请输入装货地的正确手机号码';
    // } else if (!that.data.zaddress || that.data.zaddress == '') {
    //   error = '请输入装货地的详细地址';
    // } else if (!that.data.xname || that.data.xname == '') {
    //   error = '请输入卸货地联系人';
    // } else if (!that.data.xphone_mob || that.data.xphone_mob == '' || !/^1[34578][0-9]{9}$/.test(that.data.xphone_mob)) {
    //   error = '请输入卸货地的正确手机号码';
    // } else if (!that.data.xaddress || that.data.xaddress == '') {
    //   error = '请输入卸货地的详细地址';
    // } else if (!that.data.goodsnew || that.data.goodsnew == '') {
    //   error = '请输入货物信息';
    // } else if (!that.data.goodsweight || that.data.goodsweight == '' || !/^\d+(\.\d+)?$/.test(that.data.goodsweight)) {
    //   error = '请输入正确的货物重量';
    // } else if (!that.data.goodaprice || that.data.goodaprice == '' || !/^\d+(\.\d+)?$/.test(that.data.goodaprice)) {
    //   error = '请输入正确的运单价';
    // } else if (!that.data.goodsdata || that.data.goodsdata == '' || !/^\d+(\.\d+)?$/.test(that.data.goodsdata)) {
    //   error = '请输入正确的运输天数';
    // } else if (that.data.date == '2018-1-1') {
    //   error = '请选择提货开始时间';
    // } else if (that.data.dates == '2018-1-1') {
    //   error = '请选择提货截止时间';
    // } else if (that.data.model[that.data.modelindex] == '请选择车型') {
    //   error = '请选择车型';
    // } else if (that.data.length[that.data.lengthindex] == '请选择车长') {
    //   error = '请选择车长';
    // } else if (that.data.weight[that.data.weightindex] == "请选择载重") {
    //   error = '请选择载重';
    // } else if (that.data.tiji[that.data.tijiindex] == '请选择体积') {
    //   error = '请选择体积';
    // } 
    if (that.data.transportId==undefined) {
      error = '请选择运输路线';
    }else if (!that.data.goodsnew || that.data.goodsnew == '') {
      error = '请输入货物信息';
    } else if (!that.data.goodsweight || that.data.goodsweight == '' || !/^\d+(\.\d+)?$/.test(that.data.goodsweight)) {
      error = '请输入正确的货物重量';
    } else if (that.data.date == '2018-1-1') {
      error = '请选择提货开始时间';
    } else if (that.data.dates == '2018-1-1') {
      error = '请选择提货截止时间';
    } else if (that.data.length!=undefined &&that.data.length.length>0 &&!/^\d+(\.\d+)?$/.test(that.data.length)) {
      error = '请输入正确的车长';
    } else if (that.data.payload != undefined && that.data.payload.length > 0 &&!/^\d+(\.\d+)?$/.test(that.data.payload)) {
      error = '请输入正确的载重';
    } else if (that.data.volume != undefined && that.data.volume.length > 0 &&!/^\d+(\.\d+)?$/.test(that.data.volume)) {
      error = '请输入正确的体积';
    }else{
      for (var i = 0; i < that.data.price2group.length; i++) {
        if (that.data.price2group[i].price == '' || !/^\d+(\.\d+)?$/.test(that.data.price2group[i].price)) {
          error = '请输入正确的运单价';
        }
      }
    }
    return error;
  },
  //提货开始时间
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  //提货截止时间
  stopdatachange: function (e) {
    console.log(e);
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      dates: e.detail.value
    })
  },
  stoptimechange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      times: e.detail.value
    })
  },
  //车型
  changemodel: function (e) {
    console.log(e);
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      modelindex: e.detail.value
    })
  },  //车长
  changelength: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      lengthindex: e.detail.value
    })
  },  //载重
  changeweight: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
     weightindex: e.detail.value
    })
  },  //体积
  changetiji: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      tijiindex: e.detail.value
    })
  },
  optionsSelect: function (e) {
    var cur = e.currentTarget.dataset.cur;
    var value = e.currentTarget.dataset.value;
    console.log(value);
    this.setData({
      options: cur,
      options_value: value,
    })
  },
  bindSelect: function (e) {
    var cur = e.currentTarget.dataset.cur;
    console.log(cur);
    this.setData({
      pallet_select: cur,
    })
  },

  call: function () {
    wx.makePhoneCall({
      phoneNumber: '18218751306' //仅为示例，并非真实的电话号码
    })
  },

 
  // 省市区
  bindChange: function (e) {
    //console.log(e);
    var val = e.detail.value
    var t = this.data.values;
    var cityData = this.data.cityData;

    if (val[0] != t[0]) {
      console.log('province no ');
      const citys = [];
      const countys = [];

      for (let i = 0; i < cityData[val[0]].sub.length; i++) {
        citys.push(cityData[val[0]].sub[i].name)
      }
      for (let i = 0; i < cityData[val[0]].sub[0].sub.length; i++) {
        countys.push(cityData[val[0]].sub[0].sub[i].name)
      }
      if (this.data.newnew=="zhuang"){
        this.setData({
          zprovince: this.data.provinces[val[0]],
          zcity: cityData[val[0]].sub[0].name,
          citys: citys,
          zcounty: cityData[val[0]].sub[0].sub[0].name,
          countys: countys,
          values: val,
          value: [val[0], 0, 0]
        })
      }else{
        this.setData({
          xprovince: this.data.provinces[val[0]],
          xcity: cityData[val[0]].sub[0].name,
          citys: citys,
          xcounty: cityData[val[0]].sub[0].sub[0].name,
          countys: countys,
          values: val,
          value: [val[0], 0, 0]
        })
      }
      

      return;
    }
    if (val[1] != t[1]) {
      console.log('city no');
      const countys = [];

      for (let i = 0; i < cityData[val[0]].sub[val[1]].sub.length; i++) {
        countys.push(cityData[val[0]].sub[val[1]].sub[i].name)
      }
      if (this.data.newnew == "zhuang") {
        this.setData({
          zcity: this.data.citys[val[1]],
          zcounty: cityData[val[0]].sub[val[1]].sub[0].name,
          countys: countys,
          values: val,
          value: [val[0], val[1], 0]
        })
      } else {
        this.setData({
          xcity: this.data.citys[val[1]],
          xcounty: cityData[val[0]].sub[val[1]].sub[0].name,
          countys: countys,
          values: val,
          value: [val[0], val[1], 0]
        })
      }
      return;
    }
    if (val[2] != t[2]) {
      console.log('county no');
      if (this.data.newnew == "zhuang") {
        this.setData({
          zcounty: this.data.countys[val[2]],
          values: val
        })
      } else {
        this.setData({
          xcounty: this.data.countys[val[2]],
          values: val
        })
      }
      return;
    }


  },
  open: function (res) {
    console.log(res);
    this.setData({
      condition: !this.data.condition,
      newnew:res.currentTarget.dataset.address
    })
  },
  //显示价格
  showprice: function () {
    var that = this;
    that.setData({
      price: that.data.price ? false : true
    })
  },

  // 提交
  submit: function () {

    var that = this;
    var options = that.data.options;
    // console.log();
    // 用户输入校验
    var virify = that.virifi();

    if (virify != '') {
      wx.showModal({
        title: '提示',
        content: virify,
        showCancel: false
      });
      return false;
    };

    // 授权
    app.getLoginSession(function (session) {

      wx.request({

        // 请求地址
        url: app.api +'/wx_log_test/sys/cargo?token='+session,
        data:{
          "cargo": {
            "cargoName": that.data.goodsnew,
            "gross": that.data.goodsweight,
            "length": that.data.length,
            "payload": that.data.payload,
            "remain": '',
            "remark": that.data.tips,
            "sendDate1": Date.parse(new Date(that.data.date + " " + that.data.time + ":00")),
            "sendDate2": Date.parse(new Date(that.data.dates + " " + that.data.times + ":00")),
            "transportId": that.data.transportId,
            "vehicle": that.data.model[that.data.modelindex],
            "volume": that.data.volume
          },
          "price2group": priceMap
        },
        method:'POST',
        header:{
          'content-type': 'application/json'
        },
        // 请求成功
        success: function (res) {
          var res = res.data;
          console.log(res);
          if(res.msg=="OK"){
            wx.reLaunch({
              url: '/pages/pallet_list/pallet_list',
            })
          }else{
            wx.showLoading({
              title: '请重试！',
              icon:'loading'
            })
          }
        },
        fail:function(res){
          wx.showLoading({
            title: '接口请求错误！',
            icon: 'loading'
          })
        }
      })
    })
  },
  //装货地
  zhuangline:function(e){
    var that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      zline: e.detail.value,
      transportId: that.data.zhuangline[e.detail.value].id
    })
    //选择完装货地后通过id获取详细信息
    var id = that.data.zhuangline[e.detail.value].id;
    // 授权
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/wx_log_test/sys/transport/' + id,
        data: {
          token: session
        },
        success:function(res){
          var res = res.data;
          if(res.msg=="OK"){
            var data = res.data;
            that.setData({
              zname:data.departure.link_man,
              zphone_mob:data.departure.telephone,
              zprovince: data.departure.province,
              zcity: data.departure.city,
              zcounty: data.departure.county,
              zaddress: data.departure.address + ' ' + data.departure.client,
              xname: data.destination.link_man,
              xphone_mob: data.destination.telephone,
              xprovince: data.destination.province,
              xcity: data.destination.city,
              xcounty: data.destination.county,
              xaddress: data.destination.address + ' ' + data.destination.client,
              period: data.period
            })
          }
        }
      })
    })
  }
})